package DBLayer;
import java.sql.*;


public class ConnectionDB {

private static String driver;
private static String databaseName;

private static String userName;
private static String password;

private DatabaseMetaData dma;
private static Connection conn;
private static ConnectionDB instance = null;



	public ConnectionDB() {
		driver = "jdbc:sqlserver://balder.ucn.dk:1433";
		databaseName = ";databaseName=dmab0913_5";
		userName = ";user=dmab0913_5";
		password = ";password=MaaGodt";
	
		String url = driver + databaseName + userName + password;
	
		System.out.println(url);

	try {
		Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
		System.out.println("Loading of driver - OK");
	}

	
	catch (Exception e) {
		System.out.println("Loading of driver - FAILED");
		System.out.println(e.getMessage());
	}
	

	try {
		conn = DriverManager.getConnection(url);
		conn.setAutoCommit(true);
		
		dma = conn.getMetaData();
	
		System.out.println("Connection to:" + dma.getURL());
		System.out.println("Driver:" + dma.getDriverName());
		System.out.println("Database product name:" + dma.getDatabaseProductName());
	}

	catch (Exception e) {
		System.out.println("Problem connection to the database");
		System.out.println(e.getMessage());
		System.out.println(url);
	}
	}

	public static ConnectionDB getInstance() {
		if (instance == null) {
			instance = new ConnectionDB();
		}
		return instance;
	}
	
	public static void closeConnection() {
		try {
			conn.close();
			System.out.println("Connection is closed");
		}
		catch (Exception e) {
			System.out.println("Error trying to close the connection" + e.getMessage());
		}
	
	}

	public static Connection getConn() {
		return conn;
	}

	public static void startTransation() {
		try {
			conn.setAutoCommit(false);
		}
		catch (Exception e) {
			System.out.println("Error stating transaction");
			System.out.println(e.getMessage());
		}
	}

	public static void commitTransation() {
		try {
			conn.setAutoCommit(true);
		}
		catch (Exception e) {
			System.out.println("Error committing transaction");
			System.out.println(e.getMessage());
		}	
		}

	public static void rollbackTransation() {
		try {
			conn.rollback();
			conn.setAutoCommit(true);
		}
		catch (Exception e) {
			System.out.println("Error rollback transaction");
			System.out.println(e.getMessage());
		}	
		}
}